package jcode.project.fileserver;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.List;

@RequestMapping(value = "/files")
@Controller
public class App {

    private static Logger logger = LoggerFactory.getLogger(App.class);

    private static File dir = null;

    @RequestMapping("/list")
    @ResponseBody
    List<String> list(HttpServletRequest request) throws IOException {
        String[] fileNames = dir.list();
        return Utils.map(Arrays.asList(fileNames), e -> e);
    }

    @RequestMapping("/upload")
    @ResponseBody
    String upload(FileData fileData, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Utils.assertNotNull(fileData.getFile());

        File destFile = destFile(fileData.getFile().getOriginalFilename());
        logger.info(fileData.getFile().getOriginalFilename() + "保存到" + destFile.getAbsolutePath());

        try (FileOutputStream out = new FileOutputStream(destFile)) {
            IOUtils.copy(fileData.getFile().getInputStream(), out);
        }

        response.sendRedirect("/index.html");
        return null;
    }

    private File destFile(String fileName) throws UnsupportedEncodingException {
        return new File(dir, fileName);
    }

    @RequestMapping("/{name}")
    @ResponseBody
    void download_bypath(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        download(name, request, response);
    }

    @RequestMapping("/download")
    @ResponseBody
    void download(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Utils.assertNotEmpty(name);

        File destFile = destFile(name);

        response.addHeader("Content-Length", destFile.length() + "");

        try (FileInputStream in = new FileInputStream(destFile)) {
            Utils.downloadAndEncodeFileName(in, request, response, name);
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    String delete(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Utils.assertNotEmpty(name);

        File destFile = destFile(name);

        destFile.delete();

        response.sendRedirect("/index.html");
        return null;
    }

    public static void main(String[] args) throws Exception {
        String dirPath = args.length >= 1 ? args[0] : ".";
        dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        SpringApplication.run(new Object[]{AppConfig.class}, args);

        logger.info("文件所在目录=" + dir.getCanonicalPath());

    }

}

class FileData {

    private MultipartFile file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }
}

